package m.framework;

import m.framework.dao.model.BaseModel;
import m.framework.exception.SystemException;
import m.framework.utils.StringUtil;

/**
 * 系统类的类型,系统不同类有不同作用,而且有各自的命名后缀,所在包名
 * 
 * @author 王永明
 * @date 2011-8-3
 */
public class ClassType {

    public static final ClassType controller = new ClassType("Controller", "controller");
    /** 数据传输对象,只有get和set方法,不包含任何业务逻辑 */
    public static final ClassType dto = new ClassType("Dto", "model");
    public static final ClassType model = new ClassType("", "model");
    public static final ClassType service = new ClassType("Service", "service");
    public static final ClassType testcase = new ClassType("Test", "test");

    private String postfix;
    private String packageName;

    
    public ClassType(String postfix, String packageName) {
        this.postfix = postfix;
        this.packageName = packageName;
    }

    public String getPostfix() {
        return postfix;
    }

    public String getPackage() {
        return packageName;
    }

    public String modelName(Class source) {
        String modelName = "";
        String pof = this.getPostfix();
        if (StringUtil.isEmpty(pof)) {
            pof = "$";
            modelName = StringUtil.getFirstBefore(source.getSimpleName(), pof);
        } else {
            modelName = StringUtil.getLastBefore(source.getSimpleName(), pof);
        }
        return modelName;
    }

    /** 通过一类获得其他类 */
    public Class getOrtherType(Class source, ClassType orther) {
        String packageName = source.getPackage().getName().replaceAll(this.getPackage() + "$", orther.getPackage());

        String modelName = this.modelName(source);
        String className = packageName + "." + modelName + orther.postfix;
        try {
            return Class.forName(className);
        } catch (ClassNotFoundException e) {
            throw new SystemException("创建类失败(" + modelName + "," + this.getPostfix() + ")" + className, e);
        }
    }

    public BaseModel newModel(Class source) {
        Class clazz = getOrtherType(source, ClassType.model);
        try {
            return (BaseModel) clazz.newInstance();
        } catch (Exception e) {
            throw new SystemException("创建" + source + "对应的model失败:" + this, e);
        }
    }

    /** 通过一类获得其他类所在包 */
    public String getOrtherPackage(Class source, ClassType orther) {
        return source.getPackage().getName().replaceAll(this.getPackage() + "$", orther.getPackage());
    }

}
